<template>
  <div class="server-selector">
    <div class="section-header">
      <el-icon class="section-icon"><Monitor /></el-icon>
      <span class="section-title">区服选择</span>
      <el-button 
        type="text" 
        size="small" 
        :loading="loading"
        @click="handleRefresh"
        class="refresh-servers-btn"
        :title="loading ? '正在刷新...' : '刷新服务器列表'"
      >
        <el-icon><Refresh /></el-icon>
      </el-button>
      <el-button 
        type="text" 
        size="small" 
        @click="checkApiHealth"
        class="health-check-btn"
        title="检查API健康状态"
      >
        <el-icon><Connection /></el-icon>
      </el-button>
    </div>
    
    <div class="server-content">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索区服名称或ID..."
          size="small"
          clearable
          prefix-icon="Search"
          class="search-input"
        />
      </div>

      <!-- 快速选择按钮 -->
      <div class="quick-select">
        <el-button size="small" @click="selectAll">全选</el-button>
        <el-button size="small" @click="selectNone">清空</el-button>
        <el-button size="small" @click="selectTop6">最新6个</el-button>
        <el-button size="small" @click="selectDefault">默认</el-button>
      </div>
      
      <!-- 服务器列表 -->
      <div class="server-list" v-loading="loading">
        <el-checkbox-group
          v-model="selectedServerIds"
          @change="handleSelectionChange"
          class="server-checkbox-group"
        >
          <div
            v-for="server in filteredServers"
            :key="`${server.platform}_${server.zone_id}`"
            class="server-item"
          >
            <el-checkbox 
              :label="`${server.platform}_${server.zone_id}`"
              class="server-checkbox"
            >
              <div class="server-info">
                <div class="server-name">
                  {{ server.platform }}_{{ server.zone_id }}
                </div>
                <div class="server-meta">
                  开服: {{ formatTimestamp(server.open_time) }}
                </div>
              </div>
            </el-checkbox>
          </div>
        </el-checkbox-group>
        
        <!-- 空状态 -->
        <el-empty
          v-if="!loading && !filteredServers.length"
          :description="searchKeyword ? '未找到匹配的区服' : '暂无服务器数据'"
          :image-size="80"
        />
      </div>
      
      <!-- 选择统计 -->
      <div class="selection-summary" v-if="selectedServerIds.length">
        <el-tag type="info" size="small">
          已选择 {{ selectedServerIds.length }} 个区服
        </el-tag>
        <el-tag
          v-if="selectedServerIds.length >= maxSelectionLimit"
          type="warning"
          size="small"
        >
          已达到最大选择限制 ({{ maxSelectionLimit }}个)
        </el-tag>
        <div v-if="filteredServers.length !== servers.length" class="filter-info">
          显示 {{ filteredServers.length }} / {{ servers.length }} 个区服
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { logger } from './utils/logger.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Monitor, Refresh, Connection, Search } from '@element-plus/icons-vue'
import { serverApi } from './api/index.ts'

// Props
const props = defineProps({
  selectedServers: {
    type: Array,
    default: () => []
  },
  servers: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:selectedServers', 'refresh'])

// 响应式数据
const selectedServerIds = ref<string[]>([])
const searchKeyword = ref('')
const maxSelectionLimit = 20

// 内部标志，防止循环更新
const isInternalUpdate = ref(false)

// 监听外部传入的选中服务器，初始化内部状态
watch(() => props.selectedServers, (newVal) => {
  if (!isInternalUpdate.value) {
    selectedServerIds.value = newVal.map((server: any) =>
      `${server.platform}_${server.zone_id}`
    )
  }
}, { immediate: true, deep: true })

// 过滤服务器列表（支持模糊搜索）
const filteredServers = computed(() => {
  if (!searchKeyword.value.trim()) {
    return props.servers
  }

  const keyword = searchKeyword.value.toLowerCase().trim()
  return props.servers.filter((server: any) => {
    const serverName = `${server.platform}_${server.zone_id}`.toLowerCase()
    const platform = server.platform.toLowerCase()
    const zoneId = server.zone_id.toString().toLowerCase()

    return serverName.includes(keyword) ||
           platform.includes(keyword) ||
           zoneId.includes(keyword)
  })
})

// 处理选择变化
const handleSelectionChange = (value: string[]) => {
  // 检查选择限制
  if (value.length > maxSelectionLimit) {
    ElMessage.warning(`最多只能选择 ${maxSelectionLimit} 个区服`)
    // 截取前 maxSelectionLimit 个
    value = value.slice(0, maxSelectionLimit)
    selectedServerIds.value = value
  } else {
    selectedServerIds.value = value
  }

  // 设置内部更新标志，防止循环
  isInternalUpdate.value = true

  // 计算选中的服务器对象
  const selectedServers = props.servers.filter((server: any) =>
    value.includes(`${server.platform}_${server.zone_id}`)
  )

  // 发送更新事件
  emit('update:selectedServers', selectedServers)

  // 下一个tick后重置标志
  nextTick(() => {
    isInternalUpdate.value = false
  })
}

// 全选
const selectAll = () => {
  const allIds = filteredServers.value.slice(0, maxSelectionLimit).map((server: any) =>
    `${server.platform}_${server.zone_id}`
  )
  handleSelectionChange(allIds)
}

// 清空选择
const selectNone = () => {
  handleSelectionChange([])
}

// 选择最新6个
const selectTop6 = () => {
  const sortedServers = [...props.servers].sort((a: any, b: any) =>
    parseInt(b.open_time || 0) - parseInt(a.open_time || 0)
  )
  const top6Ids = sortedServers.slice(0, 6).map((server: any) =>
    `${server.platform}_${server.zone_id}`
  )
  handleSelectionChange(top6Ids)
}

// 选择默认配置 (sy_2, sy_188 和4个最新区服)
const selectDefault = () => {
  const defaultServers: any[] = []
  // 查找指定的服务器
  const sy2 = props.servers.find((server: any) => server.platform === 'sy' && server.zone_id === '2')
  const sy188 = props.servers.find((server: any) => server.platform === 'sy' && server.zone_id === '188')

  if (sy2) defaultServers.push(...[sy2])
  if (sy188) defaultServers.push(...[sy188])

  // 添加4个最新区服
  const sortedServers = [...props.servers].sort((a: any, b: any) =>
    parseInt(b.open_time || 0) - parseInt(a.open_time || 0)
  )

  // 排除已添加的 sy_2 和 sy_188
  const latestServers = sortedServers.filter((server: any) =>
    !(server.platform === 'sy' && (server.zone_id === '2' || server.zone_id === '188'))
  ).slice(0, 4)

  defaultServers.push(...latestServers)

  // 确保不超过最大选择限制
  const finalServers = defaultServers.slice(0, maxSelectionLimit)
  const defaultIds = finalServers.map((server: any) =>
    `${server.platform}_${server.zone_id}`
  )

  handleSelectionChange(defaultIds)
}

// 处理刷新按钮点击
const handleRefresh = () => {
  emit('refresh')
}

// 检查API健康状态
const checkApiHealth = async () => {
  try {
    ElMessage.info('正在检查API健康状态...')
    const healthResults = await serverApi.checkHealth()
    
    // 构建健康状态报告
    let report = '服务器API健康状态检查结果:\n\n'
    healthResults.forEach(result => {
      const status = result.status === 'success' ? '✅ 正常' : '❌ 失败'
      const responseTime = result.responseTime ? `${result.responseTime}ms` : 'N/A'
      report += `${result.url}: ${status} (响应时间: ${responseTime})\n`
      if (result.error) {
        report += `  错误: ${result.error}\n`
      }
    })
    
    // 显示结果
    await ElMessageBox.alert(report, 'API健康状态', {
      confirmButtonText: '确定',
      type: 'info'
    })
    
  } catch (error: any) {
    console.error('健康检查失败:', error)
    ElMessage.error(`健康检查失败: ${error.message}`)
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp: any) => {
  if (!timestamp || timestamp === 0) return '未知'
  try {
    return new Date(parseInt(timestamp) * 1000).toLocaleDateString('zh-CN')
  } catch {
    return '无效时间'
  }
}
</script>

<style scoped>
.server-selector {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.section-icon {
  color: #409eff;
  font-size: 18px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
  flex: 1;
}

.refresh-servers-btn {
  color: #409eff;
}

.health-check-btn {
  color: #67c23a;
}

.server-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-section {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.search-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: rgba(255, 255, 255, 0.4);
}

.search-input :deep(.el-input__inner) {
  background: transparent;
  border: none;
  color: #ffffff;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.quick-select {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.server-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  padding: 12px;
  background: rgba(0, 0, 0, 0.2);
}

.server-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.server-item {
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.server-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.server-checkbox {
  width: 100%;
}

.server-checkbox :deep(.el-checkbox__label) {
  width: 100%;
  padding-left: 8px;
}

.server-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.server-name {
  font-weight: bold;
  color: #ffffff;
  font-size: 14px;
}

.server-meta {
  font-size: 12px;
  color: #999;
}

.selection-summary {
  text-align: center;
  padding-top: 8px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.filter-info {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 4px;
}

/* 自定义滚动条 */
.server-list::-webkit-scrollbar {
  width: 6px;
}

.server-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.server-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.server-list::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}
</style>
